package com.ywq.app.biz.impl.epay;

import java.net.URL;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.ywq.app.biz.AlipayBiz;
import com.ywq.common.exception.AppBusinessException;



public class AlipayBizImpl implements AlipayBiz {

	// 付宝提供给商户的服务接入网关URL
	private String gateway;
	public void setGateway(String gateway) {
		this.gateway = gateway;
	}
	
	//网站URL
	private String server;
	public String getServer() {
		return server;
	}
	public void setServer(String server) {
		this.server = server;
	}

	@Override
	public String login(Map<String, String> sParaTemp) {

		// 增加基本配置
		sParaTemp.put("service", "alipay.auth.authorize");
		sParaTemp.put("target_service", "user.auth.quick.login");
		sParaTemp.put("partner", AlipayConfig.PARTNER);
		sParaTemp.put("return_url", server+AlipayConfig.LOGIN_RETURN_URL);
		sParaTemp.put("_input_charset", AlipayConfig.INPUT_CHARSET);

		String strButtonName = "确认";

		return AlipaySubmit
				.buildForm(sParaTemp, gateway, "post", strButtonName);
	}

	@Override
	public String pay(Map<String, String> sParaTemp) {

		// 增加基本配置
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.PARTNER);
		sParaTemp.put("return_url", server+AlipayConfig.ALIPAYTO_RETURN_URL);
		sParaTemp.put("notify_url", server+AlipayConfig.ALIPAYTO_NOTIFY_URL);
		sParaTemp.put("seller_email", AlipayConfig.SELLER_EMAIL);
		sParaTemp.put("_input_charset", AlipayConfig.INPUT_CHARSET);

		String strButtonName = "确认";

		return AlipaySubmit
				.buildForm(sParaTemp, gateway, "post", strButtonName);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String timestamp() throws AppBusinessException {
		try {

			// 构造访问query_timestamp接口的URL串
			String strUrl = gateway + "service=query_timestamp&partner="
					+ AlipayConfig.PARTNER;
			StringBuffer result = new StringBuffer();

			SAXReader reader = new SAXReader();
			Document doc = reader.read(new URL(strUrl).openStream());

			List<Node> nodeList = doc.selectNodes("//alipay/*");

			for (Node node : nodeList) {
				// 截取部分不需要解析的信息
				if (node.getName().equals("is_success")
						&& node.getText().equals("T")) {
					// 判断是否有成功标示
					List<Node> nodeList1 = doc
							.selectNodes("//response/timestamp/*");
					for (Node node1 : nodeList1) {
						result.append(node1.getText());
					}
				}
			}

			return result.toString();
		} catch (Exception e) {
			throw new AppBusinessException(e);
		}
	}

	@Override
	public boolean verify(Map<String, String> params) {
		return AlipayNotify.verify(params);
	}

}
